<template>
  <div class="color-picker fbc">
    <div class="active-color">
      <input type="color" :value="selectColor"
      @input="updateColor" class="color"
      :class="selectColor"/>
    </div>

    <div class="select-color-right" >
      <button class="select-color-item"
      
      v-for="(item, index) of colorList" 
      :key="index"
      :style="{backgroundColor: item}"
      :class="item"
      @click.stop="selectColorChange(item)"></button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useEyeDropper } from '@vueuse/core'
const { open, sRGBHex } = useEyeDropper()
// 引入 Vue 相关的 API
import { ref, watch } from "vue";
import colorNameToHex from './utils'

// 定义组件的 props 和 emits
const props = defineProps<{defaultColor: string}>()

const emit = defineEmits(["change"]);

const colorList = ['#ffffff', '#1677ff', '#00b96b', '#F5222D', '#ff8000', '#ffff00', '#00ffff', '#cccccc', '#000000','transparent']

const selectColor = ref<string>('') //派发的颜色

const selectColorChange = (color: string) => {
  
  // document.execCommand('forecolor', true, color)
  // console.log(1111111111)
  selectColor.value = color
}

//监听接受的值然后进行复制
watch(() => props.defaultColor, async (newValue) => {
  if (newValue) {
    selectColor.value = colorNameToHex(newValue);
  }
}, { immediate: true })

//监听滴管颜色
watch(sRGBHex, async (newModelValue) => {
  if (newModelValue) {
    selectColor.value = newModelValue;
  }
})

//监听值的变化
watch(selectColor, async (newValue) => {
  if (newValue) {
    // console.log(newValue)
    
    emit("change", newValue);
  }
})

//获取颜色盘的颜色
const updateColor = (event) => {
  selectColor.value = event.target.value;
};

//处理打开滴管时候按Esc按钮报错
const handleOpen = () => {
  try {
    open();
  } catch (error) {
    console.error('Error while opening EyeDropper:', error);
  }
};


</script>

<style lang="scss" scoped>
.color-picker {
  display: flex;
  padding: 5px 0;
  .active-color {
    cursor: pointer;
    position: relative;
    margin-right: 10px;
    
    input[type="color"].transparent::-webkit-color-swatch {
      background: url(../../assets/image/下载.png) !important;
      background-repeat: repeat;
      cursor: pointer;
    }
    
  }
  .select-color-right {
    display: flex;
    flex-wrap: wrap;
    // width: 200px;
    .select-color-item {
      cursor: pointer;
      width: 20px;
      height: 20px;
      border-radius: 4px;
      margin-right: 6px;
      margin-bottom: 5px;
      border: 1px solid #ccc;
    }
    .select-color-item.transparent {
      background: url(../../assets/image/下载.png) !important;
      background-repeat: repeat;
    }
  }

  input {
    padding: 0px;
    margin: 0px;
    width: 40px;
    height: 35px;
    cursor: pointer;
  }
  input[type="color"]::-webkit-color-swatch-wrapper {
    padding: 0;
    cursor: pointer;
  }

  input[type="color"]::-webkit-color-swatch {
    border: none;
    cursor: pointer;
  }
}



</style>./utils